#!/usr/bin/env python
# coding=utf-8
import os
import re
import json
import sys

"""
python port_discover.py  "userapp.8080-ftp.21"
"""


def check_custom_name(args):
    if len(sys.argv) == 2:
        macro = sys.argv[1]
        all_keys = (args.keys())
        # macros = "userapp.8080-ftp.21"
        macro = macro.split('-')
        for i in macro:
            res = i.split('.')
            app_name = res[0]
            app_port = res[1]
            if app_port in all_keys:
                args[app_port] = app_name
    else:
        # 如果没有模板传入变量就返回空字典
        args.clear()

    return args


def port_dict():
    drop_list = ['25', '111', 'sshd', 'zabbix_agent']
    # 排除端口
    drop_str = "|".join(drop_list)

    cmd = """ netstat -pntl | awk '/[0-9]\//{print $4,$7}'|sed  's/:$//' |sed 's_.*\:__' |sed 's#[ ][0-9].*\/#:#g'|sort |uniq | egrep -vw '%s'""" % (
        drop_str)
    result_str = os.popen(cmd)
    # 返回结果 端口和进程名

    service_dict = {}

    for line in result_str:
        port_reg = re.search(r"(\d+)\:(\S+)", line)
        if port_reg is not None:
            match_line = (port_reg.groups())
            service_dict[match_line[-2]] = match_line[-1]
    # 校验是否有zabbix自定义服务名
    service_dict = check_custom_name(service_dict)
    return service_dict


def json_zabbix(args):
    ports = []
    for key in args:
        ports += [{'{#PNAME}': args[key], '{#PPORT}': key}]
    return json.dumps({'data': ports}, sort_keys=True, indent=4, separators=(',', ':'))
    # 格式化成适合zabbix lld的json数据


if __name__ == "__main__":
    if len(sys.argv) != 1:
        local_port= port_dict()
        print(json_zabbix(local_port))
